<!-- 页面 -->
<template>
	<s-layout title="选择渠道" >
		<view>
			<view
					class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20 ss-p-x-40"
					v-for="(order,index) in state.pagination.data"
					:key="order.id"
			>
				<view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
					<view
							v-if="index <= 2"
							style="
					background-color: #f31000;
					color: #fff;
					font-size: 15px;
					padding: 2px 4px;
					border-radius: 2px;
					position: absolute;
					top: 30rpx;
					right: 30rpx;
					z-index: 2;
					font-weight: bold;
				">推荐</view>
					<view style="font-size: 35rpx; font-weight: bold;">{{ order.dictLabel }}</view>
				</view>
				<view class="border-bottom" style="padding: 20rpx">
					{{ order.remark }}
				</view>
				<view
						class="order-card-footer ss-flex ss-col-center ss-p-x-20"
				>
					<view class="ss-flex ss-col-center ml-auto">
						<!--<button class="tool-btn ss-reset-button ui-BG-Main-Gradient"
						        @tap.stop="onViewRule(order)">
							渠道规则
						</button>-->
						<button class="tool-btn ss-reset-button ui-BG-Main-Gradient"
						        @tap.stop="onConfirm(order)">
							选择
						</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载更多 -->
		<uni-load-more
				v-if="state.pagination.total > 0"
				:status="state.loadStatus"
				:content-text="{
        contentdown: '上拉加载更多',
      }"
				@tap="loadmore"
		/>
	</s-layout>
</template>

<script setup>
import { computed, reactive } from 'vue';
import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import _, {clone} from 'lodash';

const pagination = {
	data: [],
	page: 1,
	total: 0,
	size: 5
};
// 数据
const state = reactive({
	currentTab: 0,
	pagination: {
		data: [],
		ruleData: [],
		page: 1,
		total: 0,
		size: 5
	},
	formData: {
		orderIdList: null,
		type: null,
		channelId: null,
		channelName: null
	},
	loadStatus: '',
	deleteOrderId: 0,
	error: 0,
});

const selectOrderIds = reactive([])

const tabMaps = [
	{
		name: '全部',
		value: '-1',
	},
	{
		name: '待付款',
		value: '0',
	},
	{
		name: '待发货',
		value: '1',
	},
	{
		name: '待收货',
		value: '2',
	},
	{
		name: '售后单',
		value: '-2',
	},
];

/**
 * 选择订单
 */
function onSelectSingle(orderId) {
	if (!selectOrderIds.includes(orderId)) {
		selectOrderIds.push(orderId);
	} else {
		selectOrderIds.splice(selectOrderIds.indexOf(orderId), 1);
	}
	console.log(selectOrderIds)
}

// 切换选项卡
function onTabsChange(e) {
	selectOrderIds.splice(0, selectOrderIds.length)
	if (state.currentTab === e.index) return;

	state.pagination = clone(pagination);
	state.currentTab = e.index;
	state.pagination.data = []
	getOrderList();
}

// 订单详情
function onOrderDetail(id) {
	sheep.$router.go('/pages/order/detail', {
		id,
	});
}

// 分享拼团
function onOrderGroupon(order) {
	sheep.$router.go('/pages/activity/groupon/detail', {
		id: order.ext.groupon_id,
	});
}

// 查看发票
function onOrderInvoice(invoiceId) {
	sheep.$router.go('/pages/order/invoice', {
		invoiceId,
	});
}

// 继续支付
function onPay(data) {
	console.log('data',data)
	sheep.$router.go('/pages/pay/index', {
		orderSN:data.orderSn,
		totalAmount: data.totalAmount,
		orderType: 'memberConsumer',
		rate: data.rate
	});
}

// 支付运费
function onDeyPay(data) {
	console.log('data',data)
	sheep.$router.go('/pages/pay/index', {
		orderSN:data.orderSn,
		totalAmount: data.totalAmount,
		orderType: 'memberConsumerDeyPay'
	});
}

// 评价
function onComment(orderSN) {
	sheep.$router.go('/pages/goods/comment/add', {
		orderSN,
	});
}

function onViewRule(order) {
	let ruleContent = '暂无规则';
	// 寻找渠道规则
	state.pagination.ruleData.forEach(item => {
		if (item.dictLabel === order.dictLabel) {
			ruleContent = item.remark;
		}
	})
	// 弹出公共框
	uni.showModal({
		title: `${order.dictLabel}渠道规则`,
		content: `${ruleContent}`,
		confirmText: '了解',
		cancelText: '关闭',
		success: function (res) {

		}
	})
}

// 确认收货
async function onConfirm(order) {
	state.formData.channelId = order.dictCode;
	state.formData.channelName = order.dictLabel;
	uni.showModal({
		title: '提示',
		content: `确认选择${order.dictLabel}渠道么`,
		success: async function (resp) {
			/*console.log(state.formData)
			const res = await sheep.$api.order.batchConfirmSendTypeForm(state.formData);
			if (res) {
				uni.reLaunch({
					url: '/pages/order/list',
				})
			}*/
			// 选择地址
			sheep.$router.go('/pages/order/express/confirm', {
				data: JSON.stringify(state.formData),
			});
		},
	});
}

// 确认合并
async function onConfirmPackSend() {
	if (selectOrderIds.length === 1) {
		// 直邮确认框
		uni.showModal({
			title: '确定采用直邮的方式么？',
			content: '您仅选择了一笔订单，那么我们将以直邮的方式计算运费',
			success: async function (res) {
				if (res.confirm) {
					const res = await sheep.$api.order.merge(selectOrderIds);
					if (res) {
						selectOrderIds.splice(0, selectOrderIds.length)
						sheep.$helper.toast('确认邮寄方式成功, 耐心等待客服计算运费')
						state.pagination = clone(pagination)
						getOrderList()
					}
				}
			},
		});
	} else {
		uni.showModal({
			title: '邮寄方式确认',
			content: `您确认这 ${selectOrderIds.length}笔 订单采用拼邮的方式一起发货么？\n 【注意事项】\n 1.订单确认邮寄方式后若客服还没设置运费，那么您可以还原重新确认邮寄方式，若已设置运费则无法还原 \n 2.多笔订单一起发货后，其余订单商品将会合并到第一笔订单中`,
			success: async function (res) {
				if (selectOrderIds.length === 0) {
					sheep.$helper.toast('请选择订单')
					return
				}
				if (res.confirm) {
					const res = await sheep.$api.order.merge(selectOrderIds);
					if (res) {
						selectOrderIds.splice(0, selectOrderIds.length)
						sheep.$helper.toast('确认邮寄方式成功, 耐心等待客服计算运费')
						state.pagination = clone(pagination)
						getOrderList()
					}
				}
			},
		});
	}
}

function batchConfirmSendType(type) {
	// 确认框
	uni.showModal({
		title: `确定采用${type === 0 ? '直邮' : '拼邮'}的方式么？`,
		content: `您选择了${selectOrderIds.length}笔订单，确认邮寄方式`,
		success: async function (res) {
			if (res.confirm) {
				sheep.$router.go('/pages/public/faq', {
					orderIds: selectOrderIds,
					type: type
				})
				// const res = await sheep.$api.order.batchConfirmSendType(selectOrderIds, type);
				// if (res) {
				// 	selectOrderIds.splice(0, selectOrderIds.length)
				// 	sheep.$helper.toast('确认邮寄方式成功, 耐心等待客服计算运费')
				// 	state.pagination = clone(pagination)
				// 	getOrderList()
				// }
			}
		},
	});
}

/**
 * 还原
 * @param order
 */
function onResetOrder(order) {
	// 确认框
	uni.showModal({
		title: '确定还原订单吗？',
		content: '【注意事项】\n 1. 订单确认邮寄方式后若客服还没设置运费，那么您可以还原重新确认邮寄方式 \n 2.若已设置运费则无法还原',
		success: async function (res) {
			if (res.confirm) {
				const res = await sheep.$api.order.reset(order.orderId);
				if (res) {
					sheep.$helper.toast('还原成功')
					state.pagination = clone(pagination)
					getOrderList()
				}
			}
		},
	});
}

// 查看物流
async function onExpress(orderId) {
	return
	sheep.$router.go('/pages/order/express/list', {
		orderId,
	});
}

// 计算商品数量
function calcGoodsCount(data){
	let sum = 0
	data.forEach(it => {
		sum += it.quantity
	})
	return sum
}

// 取消订单
async function onCancel(orderId) {
	uni.showModal({
		title: '提示',
		content: '确定要取消订单吗?',
		success: async function (res) {
			if (res.confirm) {
				const idList = [orderId]
				const res = await sheep.$api.order.cancel({idList});
				if (res) {
					sheep.$helper.toast('取消成功')
					state.pagination = clone(pagination)
					getOrderList()
				}
			}
		},
	});
}

// 删除订单
function onDelete(orderId) {
	uni.showModal({
		title: '提示',
		content: '确定要删除订单吗?',
		success: async function (res) {
			if (res.confirm) {
				const { error, data } = await sheep.$api.order.delete(orderId);
				if (error === 0) {
					let index = state.pagination.data.findIndex((order) => order.id === orderId);
					state.pagination.data.splice(index, 1);
				}
			}
		},
	});
}

// 申请退款
async function onRefund(order) {
	uni.setStorageSync("refundOrder", JSON.stringify(order))
	sheep.$router.go('/pages/order/aftersale/apply')
}

async function cancelRefund(id) {
	uni.showModal({
		title: '提示',
		content: '确定要取消售后吗?',
		success: async function (res) {
			if (res.confirm) {
				await sheep.$api.order.aftersale.cancel(id);
				sheep.$helper.toast('取消成功')
				reloadData();
			}
		},
	});
}

// 获取订单列表
async function getOrderList() {
	state.loadStatus = 'loading';
	console.log('size:', state.pagination)
	let res = await sheep.$api.order.channelList({});
	state.pagination.data = res;
	let ruleRes = await sheep.$api.order.channelList({ type: 'channel_rule' });
	state.pagination.ruleData = ruleRes;
	console.log(state)
}

onLoad(async (options) => {
	console.log(options)
	state.formData.mergeOrderIdList = options.orderIds.split(',')
	state.formData.sendType = options.type
	console.log(state.formData)
	getOrderList();
});

// 加载更多
function loadmore() {
	if (state.loadStatus !== 'noMore') {
		state.pagination.page++
		getOrderList();
	}
}

// 上拉加载更多
onReachBottom(() => {
	loadmore();
});

//下拉刷新
onPullDownRefresh(() => {
	state.pagination = clone(pagination);
	getOrderList();
	setTimeout(function () {
		uni.stopPullDownRefresh();
	}, 800);
});

function reloadData(){
	state.pagination = clone(pagination)
	getOrderList()
}
</script>

<style lang="scss" scoped>
.score-img {
	width: 36rpx;
	height: 36rpx;
	margin: 0 4rpx;
}
.tool-btn {
	width: 160rpx;
	height: 55rpx;
	background: white;
	font-size: 26rpx;
	border-radius: 30rpx;
	margin-right: 10rpx;

	&:last-of-type {
		margin-right: 0;
	}
}
.delete-btn {
	width: 160rpx;
	height: 55rpx;
	color: #F39800;
	background: #fee;
	border-radius: 30rpx;
	font-size: 26rpx;
	margin-right: 10rpx;
	line-height: normal;
	border: 1rpx solid #F39800;

	&:last-of-type {
		margin-right: 0;
	}
}

.apply-btn {
	width: 160rpx;
	height: 55rpx;
	border-radius: 30rpx;
	font-size: 26rpx;
	border: 2rpx solid #dcdcdc;
	line-height: normal;
	margin-left: 10rpx;

	&:last-of-type {
		margin-right: 0;
	}
}

.swiper-box {
	flex: 1;

	.swiper-item {
		height: 100%;
		width: 100%;
	}
}

.order-list-card-box {
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 1px 1px 10px #d7d7d7;
  border-radius: 20rpx;
  padding: 5rpx;

  .tag {
    flex-shrink: 0;
    padding: 4rpx 10rpx;
    font-size: 24rpx;
    font-weight: 500;
    border-radius: 4rpx;
    color: #ffffff !important;
    background: #F39800;
  }


  .order-card-header {
    height: 80rpx;

    .order-no {
      font-size: 26rpx;
      font-weight: 500;
    }

    .order-state {
    }
  }

  .pay-box {
    .discounts-title {
      font-size: 24rpx;
      line-height: normal;
      color: #999999;
      margin-right: 20rpx;
    }

    .discounts-money {
      font-size: 24rpx;
      line-height: normal;
      color: #999;
      font-family: OPPOSANS;
    }

    .pay-color {
      color: #333;
    }
  }

  .order-card-footer {
    height: 100rpx;

    .more-item-box {
      padding: 20rpx;

      .more-item {
        height: 60rpx;

        .title {
          font-size: 26rpx;
        }
      }
    }

    .more-btn {
      color: $dark-9;
      font-size: 24rpx;
    }

    .content {
      width: 154rpx;
      color: #333333;
      font-size: 26rpx;
      font-weight: 500;
    }
  }
}

:deep(.uni-tooltip-popup) {
	background: var(--ui-BG);
}
.warning-color {
	color: #F39800;
}
.danger-color {
	color: #F39800;
}
.success-color {
	color: #52c41a;
}
.info-color {
	color: #999999;
}

:deep() {
	checkbox .wx-checkbox-input {
		border-radius: 50% !important;
		color: #ffffff !important;
	}

	checkbox .wx-checkbox-input.wx-checkbox-input-checked {
		color: #fff;
		background: var(--ui-BG-Main);
	}

	.wx-checkbox-input.wx-checkbox-input-checked {
		border: none !important;
	}

	.uni-checkbox-input {
		border-radius: 50% !important;
		color: #ffffff !important;
	}

	.uni-checkbox-input:hover {
		border-color: #d1d1d1 !important;
	}
}

:deep(.ui-fixed) {
	height: 72rpx;
}

.cart-box {
	width: 100%;

	.cart-header {
		height: 70rpx;
		background-color: #f6f6f6;
		width: 100%;
		position: fixed;
		left: 0;
		top: v-bind('sys_navBar') rpx;
		z-index: 1000;
		box-sizing: border-box;
	}

	.cart-footer {
		height: 100rpx;
		background-color: #fff;

		.pay-btn {
			display: inline-block;
			width: 60rpx;
			height: 70rpx;
			font-size: 28rpx;
			line-height: 28rpx;
			font-weight: 500;
			border-radius: 40rpx;
		}
	}

	.cart-content {
		margin-top: 70rpx;
		.goods-box {
			background-color: #fff;
		}
	}
}
</style>
